// 配置参数
const config = {
        // 抢兑个数控制：1-只抢最后一个商品，2-抢所有符合条件的商品
            qdgs: 2,
                // 每个商品的请求次数
                    runNumber: 2,
                        // 场次检测开始执行的时间
                            targetTimes: ['09:59:59:900', '13:59:59:900'],
                                // 微信通知标题前缀
                                    notifyTitle: '电信金豆兑换通知'
};

// 引入所需模块
const tool = require('./tools/tool.js');
const moment = require('moment');
const axios = require('axios').default;
const fs = require('fs');
const CryptoJS = require('crypto-js');
const JSEncrypt = require('node-jsencrypt');
const { sendNotify } = require('./sendNotify.js');

// 加密相关配置
const pubKey = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBkLT15ThVgz6/NOl6s8GNPofdWzWbCkWnkaAm7O2LjkM1H7dMvzkiqdxU02jamGRHLX/ZNMCXHnPcW/sDhiFCBN18qFvy8g6VYb9QtroI09e176s+ZCtiv7hbin2cCTj99iUpnEloZm19lwHyo69u5UMiPMpq0/XKBO8lYhN/gwIDAQAB`;
const decrypt = new JSEncrypt();
decrypt.setPrivateKey(pubKey);

// 全局变量
let userPhone = []; // 用户账号列表
let Cache = {}; // 用户登录缓存
let CacheRunJs = 'CacheRunJs.js'; // 缓存JS文件
let initialCookie = {}; // 初始Cookie
let runUser = []; // 待抢兑用户列表
let runAxiosList = []; // 抢兑请求列表

// 初始化用户账号
function initUserAccounts() {
        if (process?.env?.dx) {
                    process.env.dx.split('\n').forEach(item => {
                                    if (item) {
                                                        const [phone, password] = item.split('#');
                                                                        userPhone.push({ phone, password });
                                    }
                    });
        } else {
                    console.error('未找到环境变量，请设置环境变量dx');
                            process.exit(1);
        }
}

// 初始化Cookie
async function initCookie(url = 'https://wapact.189.cn:9001/gateway/standExchange/detailNew/exchange') {
        try {
                    const response = await axios.post(url).catch(async err => {
                                    const htmls = String(err.response.data);
                                                const cookie = err.response.headers['set-cookie'][0].split(';')[0] + ';';
                                                            
                                                                        let cfarr = htmls.split(' content="')[2] ? 
                                                                                        htmls.split(' content="')[2].split('" r=') : 
                                                                                                        htmls.split(' content="')[1].split('" r=');
                                                                                                                    
                                                                                                                                const content = 'content="' + cfarr[0] + '"';
                                                                                                                                            const ruisuConetnt = fs.readFileSync('ruisu.js', 'utf8');
                                                                                                                                                        let newContent = ruisuConetnt.replace('content="content_code"', content);
                                                                                                                                                                    
                                                                                                                                                                                const code1 = htmls.split('$_ts=window')[1].split('</script><script type="text/javascript"')[0];
                                                                                                                                                                                            const code1Content = '$_ts=window' + code1;
                                                                                                                                                                                                        
                                                                                                                                                                                                                    const Url = htmls.split('$_ts.lcd();</script><script type="text/javascript" charset="utf-8" src="')[1].split('" r=')[0];
                                                                                                                                                                                                                                const parsedUrl = new URL(url);
                                                                                                                                                                                                                                            const downloadUrl = parsedUrl.origin + Url;
                                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                                                    let CacheRunData = '';
                                                                                                                                                                                                                                                                                try {
                                                                                                                                                                                                                                                                                                    CacheRunData = fs.readFileSync(CacheRunJs, 'utf8');
                                                                                                                                                                                                                                                                                } catch (error) {
                                                                                                                                                                                                                                                                                                    console.log('缓存JS文件不存在，从远程下载...');
                                                                                                                                                                                                                                                                                                                    CacheRunData = await downloadFile(downloadUrl, CacheRunJs);
                                                                                                                                                                                                                                                                                }
                                                                                                                                                                                                                                                                                            
                                                                                                                                                                                                                                                                                                        newContent = newContent + code1Content + CacheRunData + " return document.cookie.split(';')[0]";
                                                                                                                                                                                                                                                                                                                    const RefreshCookie = new Function(newContent);
                                                                                                                                                                                                                                                                                                                                
                                                                                                                                                                                                                                                                                                                                            return { cookie, RefreshCookie };
                    });
                            
                                    return response;
        } catch (error) {
                    console.error('初始化Cookie失败:', error);
                            return await initCookie();
        }
}

// 下载文件
async function downloadFile(url, filePath) {
        try {
                    const response = await axios.get(url);
                            fs.writeFileSync(filePath, response.data, 'utf8');
                                    return response.data;
        } catch (error) {
                    console.error('下载文件失败:', error);
                            throw error;
        }
}

// 用户登录
async function loginPhone(phone, password) {
        try {
                    const timestamp = tool.TIMEstamp();
                            const rdmstr = tool.randomString(16);
                                    
                                            // 加密处理
                                                    const encrypttext = decrypt.encrypt(`iPhone 14 15.4.${rdmstr.substring(0, 12)}${phone}${timestamp}${password}0$$$0.`);
                                                            
                                                                    // 电话号码处理
                                                                            let strphone = '';
                                                                                    for (let a of phone) {
                                                                                                    if (a <= 7) {
                                                                                                                        strphone += String(Number(a) + 2);
                                                                                                    } else {
                                                                                                                        strphone += a == 8 ? ':' : ';';
                                                                                                    }
                                                                                    }
                                                                                            
                                                                                                    // 登录请求数据
                                                                                                            const data = {
                                                                                                                            "headerInfos": {
                                                                                                                                                "code": "userLoginNormal",
                                                                                                                                                                "timestamp": timestamp,
                                                                                                                                                                                "broadAccount": "",
                                                                                                                                                                                                "broadToken": "",
                                                                                                                                                                                                                "clientType": "#9.6.1#channel50#iPhone 14 Pro Max#",
                                                                                                                                                                                                                                "shopId": "20002",
                                                                                                                                                                                                                                                "source": "110003",
                                                                                                                                                                                                                                                                "sourcePassword": "Sid98s",
                                                                                                                                                                                                                                                                                "token": "",
                                                                                                                                                                                                                                                                                                "userLoginName": phone
                                                                                                                            },
                                                                                                                                        "content": {
                                                                                                                                                            "attach": "test",
                                                                                                                                                                            "fieldData": {
                                                                                                                                                                                                    "loginType": "4",
                                                                                                                                                                                                                        "accountType": "",
                                                                                                                                                                                                                                            "loginAuthCipherAsymmertric": encrypttext,
                                                                                                                                                                                                                                                                "deviceUid": rdmstr,
                                                                                                                                                                                                                                                                                    "phoneNum": strphone,
                                                                                                                                                                                                                                                                                                        "isChinatelecom": "0",
                                                                                                                                                                                                                                                                                                            
                                                                                                                                                                            }
                                                                                                                                        }
                                                                                                                            }
                                                                                                            }
                                                                                                    }
                                                                                                    }
                                                                                    }
        }
}
        }
        }
}
        }
                                                                                                                                                                                                                                                                                }
                                                                                                                                                                                                                                                                                }
                    })
        }
}
        }
                                    }
                    })
        }
}
}